#include "songdelegate.h"
SongDelegate::SongDelegate(QTreeWidget* tw, QObject *parent)
: QStyledItemDelegate(parent)
, _tw(tw)
{


}

SongDelegate::~SongDelegate()
{

}

void SongDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	painter->save();
	QStyledItemDelegate::paint(painter, option, index);
	QModelIndex dataIndex = index.sibling(index.row(), 0);

	auto data = dataIndex.data(UserRole::SongDisplayData).value<SongItemDisplay>();
	painter->save();
	QColor clr{ 78, 226, 255, 180 };

	if(option.state& QStyle::StateFlag::State_MouseOver)
	{
		data._time = std::chrono::high_resolution_clock::now();
	
		const_cast<QAbstractItemModel*>(dataIndex.model())->setData(dataIndex, QVariant::fromValue(data), SongDisplayData);
	}
	else
	{


		auto now = std::chrono::high_resolution_clock::now();
		auto time = now - data._time;

		double ms = std::chrono::duration<double, std::chrono::milliseconds::period>(time).count();

		int alpha = 180-ms;
	
		alpha = std::max(0, alpha);
	
		clr.setAlpha(alpha);

	}
	painter->fillRect(option.rect, clr);

	painter->restore();

	if(index.column() == 0)
	{
		data.drawPlayingState(painter, option);
	}
	else if(index.column() == 1)
	{
		data.drawTitle(painter, option);
	}
	else if(index.column() == 2)
	{
		data.drawButtons(painter, option);
	}



	painter->restore();
}

QSize SongDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	auto data = index.sibling(index.row(), 0).data(UserRole::SongDisplayData).value<SongItemDisplay>();


	auto size = data.sizeHint(option, index);


	if(size.isEmpty())
	{
		size = QStyledItemDelegate::sizeHint(option, index);
	}

	// 	if(_tw && !_tw->selectionModel()->selectedIndexes().empty())
	// 	{
	// 		if(_tw->selectionModel()->selectedIndexes().front() == index)
	// 		{
	// 			size = { size.width(), 35 };
	// 		}
	// 	}
	if(_tw && _tw->selectionModel()->currentIndex().isValid())
	{
		if(_tw->selectionModel()->currentIndex() == index)
		{
			size = { size.width(), 35 };
		}
	}
	return size;
}

bool SongDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
	auto data = index.sibling(index.row(), 0).data(UserRole::SongDisplayData).value<SongItemDisplay>();

	return data.editorEvent(event, model, option, index);

}
